const { debug, logError } = require('../utils/log4j');

module.exports = async function(ctx, next) {
  const start = Date.now();
  const { method, url, ip } = ctx.request;
  const userAgent = ctx.request.headers['user-agent'];
  const remoteAddress = ctx.headers['x-forwarded-for'] || ctx.ip || ctx.ips
  const logMessage = `${method} ${url} ${ip} ${userAgent} ${remoteAddress}`;
  
  try {
    await next();
    const ms = Date.now() - start;
    const logText = `${logMessage} ${ ctx.status } ${ms}ms\n 请求参数: ${JSON.stringify(ctx.request.body)} 响应参数: ${JSON.stringify(ctx.body)}`;
    debug(logText)
  } catch (error) {
    console.error(error.toString());
    const ms = Date.now() - start;
    const logText = `${logMessage} ${error.status || 500} ${ms}ms\n${error}\n${error.stack}`;
    logError(logText)
    // throw error;
    ctx.body = {
      msg: '系统异常',
      code: 500
    }
  }
};